﻿using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Webdiyer.AspNetCore;
using ZhongKeSite.Common;
using ZhongKeSite.Entity;
using ZhongKeSite.Repository;

namespace ZhongKeSite.Service
{
    public class PortalService : IPortalService
    {
        INewsRepository newsRepository;
        ISinglePageRepository singlePageRepository;
        IMileStoneRepository mileStoneRepository;
        IHonorRepository honorRepository;
        IPartnerRepository partnerRepository;
        IExpertRepository expertRepository;
        IFAQsRepository faqsRepository;
        IDownLoadRepository downLoadRepository;
        ITechnologyServiceRepository technologyServiceRepository;
        ICategoryRepository categoryRepository;
        ISubscribeRepository subscribeRepository;
        ISmtpConfigRepository smtpConfigRepository;
        ISmtpTemplateRepository smtpTemplateRepository;
        public PortalService(INewsRepository _newsRepository, ISinglePageRepository _singlePageRepository, IMileStoneRepository _mileStoneRepository
            , IHonorRepository _honorRepository, IPartnerRepository _partnerRepository, IExpertRepository _expertRepository, ICategoryRepository _categoryRepository
            , IFAQsRepository _faqsRepository, IDownLoadRepository _downLoadRepository, ITechnologyServiceRepository _technologyServiceRepository
            , ISubscribeRepository _subscribeRepository, ISmtpConfigRepository _smtpConfigRepository, ISmtpTemplateRepository _smtpTemplateRepository)
        {
            newsRepository = _newsRepository;
            singlePageRepository = _singlePageRepository;
            mileStoneRepository = _mileStoneRepository;
            honorRepository = _honorRepository;
            partnerRepository = _partnerRepository;
            expertRepository = _expertRepository;
            faqsRepository = _faqsRepository;
            downLoadRepository = _downLoadRepository;
            technologyServiceRepository = _technologyServiceRepository;
            categoryRepository = _categoryRepository;
            subscribeRepository = _subscribeRepository;
            smtpConfigRepository = _smtpConfigRepository;
            smtpTemplateRepository = _smtpTemplateRepository;
        }

        #region 前台
        /// <summary>
        /// 新闻
        /// </summary>
        /// <returns></returns>
        public NewsInfo GetNewsInfo()
        {
            NewsInfo newsInfo = new NewsInfo();
            News news = newsRepository.GetList(k => k.NewsType == NewsType.News.ToString() && k.IsRecommend == 1 && k.IsAvailable == 1 && k.IsDel == 0).FirstOrDefault();
            Expression<Func<News, bool>> predicate = s => s.NewsType == NewsType.News.ToString() && s.IsAvailable == 1 && s.IsDel == 0;
            if (news != null)
            {
                predicate = predicate.And(k => k.ID != news.ID);
            }
            newsInfo.RecommendNews = news;
            newsInfo.NewsList = newsRepository.GetList(predicate).ToList();
            return newsInfo;
        }
        /// <summary>
        /// 新闻详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public NewsDetail GetNewsDetailInfo(string id)
        {
            NewsDetail newsDetail = new NewsDetail();
            News news = newsRepository.GetById(id);
            newsDetail.News = news;

            News preNews = newsRepository.GetList(k => k.NewsType == news.NewsType && k.IsAvailable == 1 && k.IsDel == 0 && k.ID != news.ID && k.SortNo <= news.SortNo).LastOrDefault();
            newsDetail.PreNews = preNews;

            News nextNews = newsRepository.GetList(k => k.NewsType == news.NewsType && k.IsAvailable == 1 && k.IsDel == 0 && k.ID != news.ID && k.SortNo >= news.SortNo).FirstOrDefault();
            newsDetail.NextNews = nextNews;

            return newsDetail;
        }
        /// <summary>
        /// 关于我们
        /// </summary>
        /// <returns></returns>
        public AboutInfo GetAboutInfo()
        {
            AboutInfo aboutInfo = new AboutInfo();
            //品牌故事
            aboutInfo.Story = singlePageRepository.GetByExpression(k => k.SingPageType == SinglePageType.AboutUS.ToString() && k.IsDel == 0);
            //里程碑
            aboutInfo.MileStoneList = mileStoneRepository.GetList(k => k.IsDel == 0).OrderByDescending(o => o.PublishDate).ToList();
            //奖项，专利
            aboutInfo.HonorList = honorRepository.GetList(k => k.IsDel == 0).OrderBy(o => o.SortNo).ToList();
            //合作伙伴
            aboutInfo.PartnerList = partnerRepository.GetList(k => k.IsDel == 0).OrderBy(o => o.SortNo).ToList();
            return aboutInfo;
        }
        /// <summary>
        /// 故事页面
        /// </summary>
        /// <returns></returns>
        public List<News> GetStoryInfo()
        {
            List<News> newsList = newsRepository.GetList(k => k.NewsType == NewsType.Story.ToString() && k.IsAvailable == 1 && k.IsDel == 0).OrderBy(s => s.SortNo).ToList();
            return newsList;
        }
        /// <summary>
        /// 创新
        /// </summary>
        /// <returns></returns>
        public InnovateInfo GetInnovateInfo()
        {
            InnovateInfo innovateInfo = new InnovateInfo();
            var newsList = newsRepository.GetPagedList(1, 5, k => k.NewsType == NewsType.Innovation.ToString()
                && k.IsRecommend == 1 && k.IsAvailable == 1 && k.IsDel == 0).OrderBy(o => o.SortNo).ToList();
            for (int i = 0; i < newsList.Count; i++)
            {
                var item = newsList[i];
                if (i == 0)
                {
                    innovateInfo.NewsFirst = item;
                }
                else if (i == 1)
                {
                    innovateInfo.NewsSecond = item;
                }
                else if (i == 2)
                {
                    innovateInfo.NewsThird = item;
                }
                else if (i == 3)
                {
                    innovateInfo.NewsFour = item;
                }
                else if (i == 4)
                {
                    innovateInfo.NewsFive = item;
                }
            }
            innovateInfo.ExpertList = expertRepository.GetList(k => k.IsDel == 0).ToList();
            return innovateInfo;
        }
        /// <summary>
        /// 创新
        /// </summary>
        /// <returns></returns>
        public PagedList<News> GetInnovateList(int pageindex, int pagesize)
        {
            return newsRepository.GetPagedList(pageindex, pagesize, k => k.NewsType == NewsType.Innovation.ToString() && k.IsAvailable == 1 && k.IsDel == 0);
        }
        /// <summary>
        /// 得到一个专家
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Expert GetExpert(string id)
        {
            return expertRepository.GetById(id);
        }
        /// <summary>
        /// 联系我们页面
        /// </summary>
        /// <returns></returns>
        public SinglePage GetContactInfo()
        {
            return singlePageRepository.GetByExpression(k => k.SingPageType == SinglePageType.ContactUS.ToString() && k.IsDel == 0);
        }
        /// <summary>
        /// 支持
        /// </summary>
        /// <returns></returns>
        public SupportInfo GetSupportInfo()
        {
            SupportInfo supportInfo = new SupportInfo();
            var categoryList = categoryRepository.GetList(k => k.IsAvailable == 1 && k.IsDel == 0).ToList();
            var faqsList = faqsRepository.GetList(s => s.IsAvailable == 1 && s.IsDel == 0).ToList();
            var serviceList = technologyServiceRepository.GetList(s => s.IsAvailable == 1 && s.IsDel == 0).ToList();
            var downLoadList = downLoadRepository.GetList(k => k.IsAvailable == 1 && k.IsDel == 0).ToList();

            List<FAQsInfo> fAQsInfos = new List<FAQsInfo>();
            categoryList.Where(k => k.CategoryType == CategoryType.FAQsType.ToString()).ToList().ForEach(s =>
            {
                FAQsInfo fAQsInfo = new FAQsInfo();
                fAQsInfo.Category = s;
                fAQsInfo.FAQsList = faqsList.Where(m => m.CategoryID == s.ID).ToList();
                fAQsInfos.Add(fAQsInfo);
            });
            supportInfo.FAQsInfoList = fAQsInfos;

            List<ServiceInfo> serviceInfos = new List<ServiceInfo>();
            categoryList.Where(k => k.CategoryType == CategoryType.ServiceType.ToString()).ToList().ForEach(s =>
            {
                ServiceInfo service = new ServiceInfo();
                service.Category = s;
                service.ServiceList = serviceList.Where(m => m.CategoryID == s.ID).ToList();
                serviceInfos.Add(service);
            });
            supportInfo.ServiceInfoList = serviceInfos;

            List<DownLoadInfo> downLoadInfos = new List<DownLoadInfo>();
            categoryList.Where(k => k.CategoryType == CategoryType.DownLoadType.ToString()).ToList().ForEach(s =>
            {
                DownLoadInfo down = new DownLoadInfo();
                down.Category = s;
                down.DownLoadList = downLoadList.Where(m => m.CategoryID == s.ID).ToList();
                downLoadInfos.Add(down);
            });
            supportInfo.DownLoadInfoList = downLoadInfos;
            return supportInfo;
        }
        public ResultResponse Subscribe(string email)
        {
            ResultResponse resultResponse = new ResultResponse();
            if (string.IsNullOrWhiteSpace(email))
            {
                resultResponse.msg = "邮箱不能为空!";
                return resultResponse;
            }
            var sub = subscribeRepository.GetByExpression(k => k.Email == email);
            if (sub != null)
            {
                resultResponse.msg = "您已经订阅过了！";
                return resultResponse;
            }
            Subscribe model = new Subscribe();
            model.ID = IdentityCreator.NextIdentity;
            model.Email = email;
            model.IsDel = 0;
            model.AddBy = email;
            model.AddDate = DateTime.Now;
            resultResponse.success = subscribeRepository.Add(model);
            resultResponse.msg = resultResponse.success ? CommonConst.Success : CommonConst.Fail;
            return resultResponse;
        }
        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="senderEmail"></param>
        /// <param name="mailTo"></param>
        /// <param name="mailcc"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="smtpServer"></param>
        /// <param name="fromEmail"></param>
        /// <param name="displayName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="port"></param>
        /// <param name="enableSsl"></param>
        public ResultResponse SendMail(EmailModel model)
        {
            ResultResponse result = new ResultResponse() { success = false, msg = CommonConst.Fail };
            SmtpConfig config = smtpConfigRepository.FirstOrDefault();
            if(config == null)
            {
                return result;
            }
            SmtpTemplate template = smtpTemplateRepository.GetByExpression(k => k.SmtpCode == "T001");
            if(template == null)
            {
                return result;
            }
            string sender = string.Format("{0}.{1}", model.lastName,model.firstName);
            string senderEmail = config.Account;
            string mailTo = config.Email;
            string mailcc = string.Empty;
            string subject = model.jobtitle;
            string body = template.Content.Replace("{name}", sender).Replace("{company}",model.company).Replace("{email}",model.email)
                .Replace("{phone}",model.phone).Replace("{country}",model.country).Replace("{message}", model.message);
            string smtpServer = config.SmtpHost;
            string fromEmail = config.Account;
            string displayName = model.jobtitle;
            string userName = config.Account;
            string password = config.Pwd;
            int port = config.Port;
            bool enableSsl = config.IsSSL == 1;

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(displayName, fromEmail));
            message.To.Add(new MailboxAddress("web1", mailTo));

            if (!string.IsNullOrEmpty(mailcc))
                message.Cc.Add(new MailboxAddress("web2", mailcc));

            message.Subject = subject;
            message.Body = new TextPart("html")
            {
                Text = body
            };
            message.ReplyTo.Add(new MailboxAddress(sender, senderEmail));

            using (var client = new SmtpClient())
            {
                client.Connect(smtpServer, port, enableSsl);
                //SMTP server authentication if needed
                client.Authenticate(userName, password);

                client.Send(message);

                client.Disconnect(true);
            }
            result.success = true;
            result.msg = CommonConst.Success;
            return result;
        }
        #endregion

    }
}
